﻿using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Aliyun.Acs.Core.Exceptions;
using Microsoft.Extensions.Configuration;
using StackExchange.Redis;
using NPOI.SS.Formula.Functions;

namespace S.Authorization.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SmsController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        private readonly IDatabase _redisDb;
        public SmsController(IConfiguration configuration, IConnectionMultiplexer redis)
        {
            _configuration = configuration;
            _redisDb = redis.GetDatabase();
        }
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="PhoneNumbers"></param>
        /// <returns></returns>
        [HttpPost("SendSms")]
        public ActionResult<string> SendSms(string PhoneNumbers)
        {
            var msg = "";
            string accessKeyId = _configuration["Aliyun:AccessKeyId"];
            string accessKeySecret = _configuration["Aliyun:AccessKeySecret"];

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest
            {
                Method = MethodType.POST,
                Domain = "dysmsapi.aliyuncs.com",
                Version = "2017-05-25",
                Action = "SendSms"
            };
            request.AddQueryParameters("PhoneNumbers", PhoneNumbers);
            request.AddQueryParameters("SignName", "智慧农业服务");
            request.AddQueryParameters("TemplateCode", "SMS_463195093");
            Dictionary<string, object> pairs = new Dictionary<string, object>
            {
                { "code", new Random().Next(100000, 1000000).ToString() }
            };
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(pairs);
            SaveVerificationCodeToRedis(PhoneNumbers, json);
            request.AddQueryParameters("TemplateParam", json);
            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                msg = System.Text.Encoding.Default.GetString(response.HttpResponse.Content);
                return Ok(new { Message = msg });
            }
            catch (ServerException e)
            {
                return BadRequest(new { Message = e.ErrorMessage });
            }
            catch (ClientException e)
            {
                return BadRequest(new { Message = e.ErrorMessage });
            }
        }
        private void SaveVerificationCodeToRedis(string phoneNumber, string json)
        {
            // 设置验证码的过期时间为5分钟
            TimeSpan expiry = TimeSpan.FromMinutes(5);
            _redisDb.StringSet(phoneNumber, json, expiry);
        }
        [HttpGet("GetVerificationCode")]
        public ActionResult<string> GetVerificationCode(string phoneNumber)
        {
            string code = _redisDb.StringGet(phoneNumber);
            if (string.IsNullOrEmpty(code))
            {
                return NotFound(new { Message = "验证码不存在或已过期" });
            }
            return Ok(new { Code = code });
        }
    }
}